package rsexplorer.rstree;

import rsexplorer.utils.FieldFilter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import rsexplorer.utils.FieldsIterator;

public class ObjectFieldTreeNode extends FieldContainerTreeNode {
    public ObjectFieldTreeNode(Object userObject, Object fieldObject) {
        this(userObject, fieldObject, 0);
    }

    public ObjectFieldTreeNode(Object userObject, Object fieldObject, FieldFilter filter) {
        this(userObject, fieldObject, filter, 0);
    }

    protected ObjectFieldTreeNode(Object userObject, Object fieldObject, int level) {
        this(userObject, fieldObject, null, level);
    }

    protected ObjectFieldTreeNode(Object userObject, Object fieldObject, FieldFilter filter, int level) {
        super(userObject, fieldObject, filter, level);
        
        init();
    }

    private void init() {
        try {
            removeAllChildren();
            FieldsIterator it = new FieldsIterator(fieldObject.getClass());

            while (it.hasNext()) {
                Field[] fields = it.next();

                for (Field f : fields) {
                    f.setAccessible(true);

                    if (shouldFilterField(f))
                        continue;

                    if (Modifier.isStatic(f.getModifiers()))
                        continue;

                    Object object = f.get(fieldObject);

                    if (object == null)
                        object = "null";

                    addChildField(f, object);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(Object userObject, Object fieldObject) {
        try {
            FieldsIterator it = new FieldsIterator(fieldObject.getClass());

            int i = 0;
            while (it.hasNext()) {
                Field[] fields = it.next();

                
                //for (int i = 0; i < children.size(); i++) {
                for (Field f : fields) {
                    //Field f = fields[i];
                    f.setAccessible(true);

                    //if (shouldFilterField(f))
                       // continue;

                    if (Modifier.isStatic(f.getModifiers()))
                        continue;

                    Object object = f.get(fieldObject);

                    if (object == null)
                        object = "null";

                    updateChildField(i, f, object);
                    i++;
                }
                i = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
